package com.tfswx.jcyw.print.bean;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Sides;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 张述江
 * @date 2023-11-01
 */
@Slf4j
@Getter
public class FileItem {

    public static final List<String> EXT_LIST = Arrays.asList("PDF", "JPG", "JPEG", "PNG");
    private final File file;
    private final BooleanProperty selectProperty = new SimpleBooleanProperty(true);

    private final IntegerProperty pageCount = new SimpleIntegerProperty(0);

    private int orientation = PageFormat.PORTRAIT;

    public FileItem(File file) {
        this.file = file;
        readPageCount();
    }

    @SneakyThrows
    private void readPageCount() {
        String extension = FilenameUtils.getExtension(file.getName());
        switch (extension.toUpperCase()) {
            case "PDF":
                try (PDDocument document = PDDocument.load(file)) {
                    int numberOfPages = document.getNumberOfPages();
                    pageCount.set(numberOfPages);
                    PDPage page = document.getPage(0);
                    PDRectangle trimBox = page.getTrimBox();
                    float width = trimBox.getWidth();
                    float height = trimBox.getHeight();
                    int rotation = page.getRotation();
                    if (rotation % 180 != 0) {
                        height = trimBox.getWidth();
                        width = trimBox.getHeight();
                    }
                    if (width > height) {
                        orientation = PageFormat.LANDSCAPE;
                    }
                }
                break;
            case "JPG":
            case "JPEG":
            case "PNG":
                pageCount.set(1);
                BufferedImage bufferedImage = ImageIO.read(file);
                if (bufferedImage.getWidth() > bufferedImage.getHeight()) {
                    orientation = PageFormat.LANDSCAPE;
                }
                break;
            default:
                pageCount.set(0);
                break;
        }

    }

    public void setSelect(boolean select) {
        selectProperty.set(select);
    }

    public String getName() {
        return file.getName();
    }

    public boolean isSelect() {
        return selectProperty.get();
    }

    @Override
    public String toString() {
        return "名字：" + getName() + "，是否选中：" + isSelect();
    }

    public void print(PrintService ps, PageFormat pageFormat) throws PrinterException, IOException {

        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet();

        // attributeSet.add(new PageRanges(1, 7));
        // 双面打印：Sides.TWO_SIDED_SHORT_EDGE
        attributeSet.add(Sides.ONE_SIDED);

        PrinterJob printerJob = PrinterJob.getPrinterJob();
        printerJob.setPrintService(ps);
        printerJob.setJobName(getName());
        pageFormat.setOrientation(orientation);

        String extension = FilenameUtils.getExtension(file.getName());
        switch (extension.toUpperCase()) {
            case "PDF":
//                try (PDDocument document = PDDocument.load(file)) {
//                    PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.SCALE_TO_FIT);
//                    printerJob.setPrintable(pdfPrintable, pageFormat);
//                    // 开始打印
//                    printerJob.print(attributeSet);
//                }

                try (PDDocument document = PDDocument.load(file)) {
                    int numberOfPages = document.getNumberOfPages();
                    PDFRenderer pdfReader = new PDFRenderer(document);
                    Printable printable = (graphics, format, index) -> {
                        if (graphics == null) {
                            return Printable.NO_SUCH_PAGE;
                        }
                        if (index >= numberOfPages) {
                            return Printable.NO_SUCH_PAGE;
                        }
                        BufferedImage img;
                        try {
                            img = pdfReader.renderImageWithDPI(index, 600);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        return printImg(img, format, graphics);
                    };
                    printerJob.setPrintable(printable, pageFormat);
                    // 开始打印
                    printerJob.print(attributeSet);

                }
                break;
            case "JPG":
            case "JPEG":
            case "PNG":
                BufferedImage img = ImageIO.read(file);

                Printable printable = (graphics, format, index) -> {
                    if (graphics == null) {
                        return Printable.NO_SUCH_PAGE;
                    }
                    if (index >= 1) {
                        return Printable.NO_SUCH_PAGE;
                    }
                    return printImg(img, format, graphics);
                };
                printerJob.setPrintable(printable, pageFormat);
                // 开始打印
                printerJob.print(attributeSet);
                break;
            default:
                break;
        }

    }

    private static int printImg(BufferedImage img, PageFormat format, Graphics graphics) {
        log.info("图片：" + img.getWidth() + "x" + img.getHeight());
        log.info("打印机：" + format.getWidth() + "x" + format.getHeight());
        log.info("打印机1：" + format.getImageableWidth() + "x" + format.getImageableHeight());
        double scaleX = format.getImageableWidth() / img.getWidth();
        double scaleY = format.getImageableHeight() / img.getHeight();
        double scale = Math.min(scaleX, scaleY);

        graphics.translate((int) ((format.getImageableWidth() - img.getWidth() * scale) / 2), (int) ((format.getImageableHeight() - img.getHeight() * scale) / 2));

        graphics.drawImage(img, 0, 0, (int) (img.getWidth() * scale), (int) (img.getHeight() * scale), null);
        return Printable.PAGE_EXISTS;
    }
}
